package cn.lanchengkeji.datafillingsystem.controller;



import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.Menu;
import cn.lanchengkeji.datafillingsystem.entity.Roles;
import cn.lanchengkeji.datafillingsystem.entity.UserRole;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.service.IMenuService;
import cn.lanchengkeji.datafillingsystem.service.IUserRoleService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"菜单 前端控制器"})
@RestController
@RequestMapping("/menu")
public class MenuController extends BaseController {

    // 日志
    private static Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Resource
    private IMenuService iMenuService;

    @Resource
    private IUsersService iUsersService;

    @Resource
    private IUserRoleService iUserRoleService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 添加菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "添加菜单", notes = "登陆才能操作")
    @ApiImplicitParams({

    })
    @RequiresAuthentication
    @RequiresPermissions("menu:create")
    @RequestMapping(value = "/insertMenu", method = RequestMethod.POST)
    public ResponseBean insertMenu(
            HttpServletRequest request,
            @RequestBody Menu menuParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "添加系统菜单", userId,"新增");

        // 插入菜单
        Menu nMenu = new Menu();
        if (Utils.notEmpty(menuParam.getTitle())) {
            nMenu.setTitle(menuParam.getTitle());
        }
        if (Utils.notEmpty(menuParam.getPath())) {
            nMenu.setPath(menuParam.getPath());
        }
        if (Utils.notEmpty(menuParam.getName())) {
            nMenu.setName(menuParam.getName());
        }
        if (Utils.notEmpty(menuParam.getSorted())) {
            nMenu.setSorted(menuParam.getSorted());
        }
        if (Utils.notEmpty(menuParam.getIcon())) {
            nMenu.setIcon(menuParam.getIcon());
        }
        if (Utils.notEmpty(menuParam.getPid())) {
            nMenu.setPid(menuParam.getPid());
        } else {
            nMenu.setPid(0);
        }
        if (Utils.notEmpty(menuParam.getComponent())) {
            nMenu.setComponent(menuParam.getComponent());
        }
        if (Utils.notEmpty(menuParam.getRedirect())) {
            nMenu.setRedirect(menuParam.getRedirect());
        }

        return iMenuService.insertMenu(nMenu);
    }


    /**
     * 修改菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "修改菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:edit")
    @RequestMapping(value = "/updateMenu", method = RequestMethod.POST)
    public ResponseBean updateMenu(
            HttpServletRequest request,
            @RequestBody Menu menuParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "修改系统菜单", userId,"修改");

        if (Utils.notEmpty(menuParam.getId())) {

            // 修改菜单
            Menu nMenu = new Menu();
            nMenu.setId(menuParam.getId());
            if (Utils.notEmpty(menuParam.getTitle())) {
                nMenu.setTitle(menuParam.getTitle());
            }
            if (Utils.notEmpty(menuParam.getPath())) {
                nMenu.setPath(menuParam.getPath());
            }
            if (Utils.notEmpty(menuParam.getName())) {
                nMenu.setName(menuParam.getName());
            }
            if (Utils.notEmpty(menuParam.getSorted())) {
                nMenu.setSorted(menuParam.getSorted());
            }
            if (Utils.notEmpty(menuParam.getIcon())) {
                nMenu.setIcon(menuParam.getIcon());
            }
            if (Utils.notEmpty(menuParam.getPid())) {
                nMenu.setPid(menuParam.getPid());
            }
            if (Utils.notEmpty(menuParam.getComponent())) {
                nMenu.setComponent(menuParam.getComponent());
            }
            if (Utils.notEmpty(menuParam.getRedirect())) {
                nMenu.setRedirect(menuParam.getRedirect());
            }

            return iMenuService.updateMenu(nMenu);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }

    /**
     * 删除菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "删除菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:delete")
    @RequestMapping(value = "/deleteMenu", method = RequestMethod.POST)
    public ResponseBean deleteMenu(
            HttpServletRequest request,
            @RequestBody Roles rolesParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "删除系统菜单", userId,"删除");

        if (Utils.notEmpty(rolesParam.getId())) {

            // 删除菜单
            Menu nMenu = new Menu();
            nMenu.setId(rolesParam.getId());
            return iMenuService.deleteMenu(nMenu);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }


    /**
     * 查看菜单：登陆后才能操作
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "查看菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("menu:view")
    @RequestMapping(value = "/selectMenu", method = RequestMethod.POST)
    public ResponseBean selectMenu(
            @RequestBody Menu menuParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        if (Utils.notEmpty(menuParam.getId())) {

            // 查询单条菜单
            Menu nMenu = new Menu();
            nMenu.setId(menuParam.getId());
            return new ResponseBean(StatusCode.OK, iMenuService.selectOneMenu(nMenu));
        } else {

            // 查询全部菜单
            return new ResponseBean(StatusCode.OK, iMenuService.selectAllMenu());
        }

    }

    /**
     * 根据登陆用户id查询菜单
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(hidden = false, value = "根据登陆用户id查询菜单", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequestMapping(value = "/selectMenusByUserId", method = RequestMethod.POST)
    public ResponseBean selectMenusByRoleId() {

        // 获取登陆系统用户名，存入日志
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);

        String userName = (String) obj;
        if (Utils.notEmpty(userName)) {
            Users users = iUsersService.getUserByName((String) obj);

            QueryWrapper<UserRole> userRoleCondition = new QueryWrapper<>();
            userRoleCondition.eq(UserRole.USER_ID, users.getId());
            List<UserRole> userRoles = iUserRoleService.list(userRoleCondition);
            List<Integer> userRoleIds = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                userRoleIds.add(userRole.getRoleId());
            }
            return new ResponseBean(StatusCode.OK, iMenuService.selectMenusByRoleIds(userRoleIds));
        } else {
            return new ResponseBean(HttpStatus.UNAUTHORIZED, 401, "Unauthorized", "");
        }

    }

}
